var express = require('express');
var router = express.Router();
var  { userModel} = require('../../model/models/login')
var jwt =  require('jsonwebtoken')


// 登录
router.post('/login',async (req,res)=>{
    let username = req.body.username
    let password = req.body.password
    let result = await userModel.findOne({username:username})
    if(result){
        if(result.password === password){
            let token = jwt.sign({username:username},'secret',{expiresIn:60*60*24})
            res.send({code:200,msg:'登录成功',token})
        }else{
            res.send({code:201,msg:'密码错误'})
        }
    }else{
        res.send({code:201,msg:'用户不存在'})
    }
})

// 注册
router.post('/register',async (req,res)=>{
    let username = req.body.username
    let result = await userModel.findOne({username:username})
    if(result){
        res.send({code:400,msg:'账户已存在' })
    }else{
        userModel.create(req.body)
        res.send({code:200,msg:'注册成功'})
    }
})

// 获取用户信息
router.get('/userInfo',async (req,res)=>{
    let token = req.headers.authorization
    let result = await userModel.findOne({username:token})
    res.json({
        code:200,
        msg:'ok',
        data:result
    })
})





module.exports = router;
